package com.ahm.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author anhaimeng
 * @title: CaptchaController
 * @projectName yeb001
 * @description: 生成验证码
 * @date 2021/9/2315:21
 */
@RestController
@Api("验证码模块")
public class CaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
/**
　　* @description: 注意：produces ：设置返回数据类型及编码
　　* @throws
　　* @author anhaimeng
　　* @date 2021/9/23 15:34
　　*/
    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha",produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        // 设置响应头
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");

        // 定义response输出类型为image/jpeg类型
        response.setContentType("image/jpeg");

        // 生成验证码
        String text = defaultKaptcha.createText();
        // 生成文本
            // 放入session
        request.getSession().setAttribute("code",text);
            // 创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        // 输出流 刷出
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            // 输出流输出图片 ，格式jpg
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null !=outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }




}
